/**
 * date: 2018年3月4日
 * from `https://www.tslang.cn/docs/handbook/variable-declarations.html`
 */

console.log('== Ts103_variable_declarations ==');

function test101(){
    for (var i = 0; i < 5; i++) {
        // capture the current state of 'i'
        // by invoking a function with its current value
        (function (i) {
            setTimeout(function () { console.log(i); }, 100 * i);
        })(i);
    }
}

// test101();

let x = 1;
if(x===1){
    let x = 2;
}

function sumMatrix(matrix: number[][]){
    let sum = 0;
    for(let i=0;i<matrix.length;i++){
        var currentRow = matrix[i];
        for(let i=0;i<currentRow.length;i++){
            sum += currentRow[i];
        }
    }

    return sum;
}

function theCityThatAlwaysSleeps() {
    let getCity;

    if (true) {
        let city = "Seattle";
        getCity = function () {
            return city;
        }
    }

    return getCity();
}

function test002(){
    for(let i=0;i<5;i++){
        setTimeout(function(){console.log(i);}, 100*i);
    }
}

let input = [1,2];
let [first, second] = input;
console.log(first);
console.log(second);

// swap variables
[first, second] = [second, first];

let input101 = [1, 2];
let [input102, input103] = [1, 2];

function f101([first, second]: [number, number]) {
    console.log(first);
    console.log(second);
}

// f101(input101); // 参照文档编写的代码, 但是报错, why?
f101([input102, input103]);

let [first101, ...rest] = [1, 2, 3, 4];
console.log(first101);
console.log(rest);

let [first102] = [1, 2, 3, 4];
console.log( first102 );

let [, second101, , fourth101] = [1, 2, 3, 4];

let obj101 = {
    a101: "foo",
    b101: 12, 
    c: "bar"
};

let {a101, b101} = obj101;

// 注意, 我们需要用括号将它括起来, 因为Javascript通常会将以 `{` 起始的语句解析为一个块。
({ a101, b101} = {a101: "baz", b101: 101});

let obj102 = {
    a102: "foo",
    b102: 12,
    c: "bar"
};

let { a102, ...passthrough } = obj102;
let total = passthrough.b102 + passthrough.c.length;

function keepWholeObject(wholeObject: {a:string, b?:number}){
    let {a,b = 1001} = wholeObject;
}

type C103 = {a:string, b?:number};
function f102({a,b}: C103): void {
    // ...
}

function f103({a,b}={a:"",b:0}): void {
    // ...
}
f103(); // ok, default to { a: "", b: 0 }

function f104({ a, b = 0 } = { a: "" }) : void{
    // ...
}
f104({ a: "yes"}); // ok, default b = 0
f104(); // ok, default to {a:""}, which then defaults b = 0
// f104({}); // error, 'a' is required if you supply an argument

let first103 = [1, 2];
let second103 = [3, 4];
let bothPlus = [0, ...first103, ...second103, 5];

let defaults102 = { food: "spicy", price: "$$", ambiance: "noisy" };
let search102 = { ...defaults102, food: "rich"};

let search103 = { food: "rich", ...defaults102 };

class C104 {
    p = 12;
    m() {}
}
let c101 =  new C104();
let clone101 = { ...c101 };
clone101.p; // ok
clone101.m(); // error!




